package com.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 *  ByteBuff常用的类型： 堆栈类型:JVM的堆空间，方便垃圾回收
 *                     直接类型:本地方法创建(native,c++实现)
 */
public class ByteBuffer {

    public static void main(String[] args) throws UnsupportedEncodingException {

        //创建ByteBuff对象
        ByteBuf byteBuf =  Unpooled.buffer(1);  //创建空的，没有内容的
        ByteBuf byteBuf1 = Unpooled.wrappedBuffer("abc".getBytes()); //有内容的

        //容量
        System.out.println(byteBuf.capacity());  //1
        System.out.println(byteBuf1.capacity()); //3

        //存内容,不影响writeIndex
        byteBuf.setByte(0,100); //-128---127
        byteBuf.setByte(0,200);
        //byteBuf1.setByte(3,100);  //容量是3，所以，下标只能是0，1，2

        //取内容,不影响readIndex
        byte b  =byteBuf.getByte(0);
        System.out.println(b);

        //打印读写索引
        int readIndex = byteBuf.readerIndex();
        int writeIndex = byteBuf.writerIndex();
        System.out.println(readIndex); //0
        System.out.println(writeIndex); //0

        //写内容 ，会改变writeIndex值
        byteBuf.writeInt(200);
        readIndex = byteBuf.readerIndex();
        writeIndex = byteBuf.writerIndex();
        System.out.println("int占4个字节:"+writeIndex); //1

        //读内容，会改变readIndex的值
        int read = byteBuf.readByte();
        System.out.println(read);  //10
        readIndex = byteBuf.readerIndex();
        System.out.println(readIndex); //1

        //byteBuf.setByte(1,20); //不能越界
         //byteBuf.writeByte(20); //写内容 ，会自动扩容
         byteBuf.ensureWritable(129);//不写内容，扩容
         System.out.println(byteBuf.capacity());

         //写字符串
        byteBuf.clear(); //把readIndex,writeIndex置0
        //byteBuf.resetReaderIndex();//把readIndex置0
        //byteBuf.resetWriterIndex();//把writeIndex置0

        String old = "智能ABC";
        byteBuf.writeBytes(old.getBytes("utf-8"));
        System.out.println(byteBuf.readerIndex());//0
        System.out.println(byteBuf.writerIndex());//9,1个汉字3字节

        //读字符串
        String resultString = byteBuf.toString(Charset.forName("utf-8"));
        System.out.println(resultString);
        System.out.println(byteBuf.readerIndex());//0







    }
}
